<?php
declare (strict_types = 1);

namespace app\api\controller\v1;

use app\api\service\StatusCode;
use think\facade\Request;
use app\api\service\UserToken as TokenService;
use app\api\validate\Account as ValidateAccount;
use think\facade\Log;

/**
 * 全站的公共资源数据
 */
class Publics extends Api
{
    /**
     * 系统登录
     */
    public function login()
    {
        $data = Request::post();
        validate(ValidateAccount::class)->scene('login')->check($data);

        $modelName = $data['from'] == 'T' ? 'Teacher' : 'Student';
        $modelName = '\app\api\model\\' . $modelName;
        $user = new $modelName();
        $userInfo = $user->checkLogin($data['account'],$data['password']);
        if( $userInfo === false ){
            $this->return_msg(StatusCode::SERVER_ERROR, $user->error);
        }

        $data = [
            'token'       => TokenService::generateAccessToken($userInfo),
            'expire_time' => config('api.token_expire_time'),
            'userinfo'    => $userInfo
        ];
        $this->return_msg(StatusCode::SUCCESS, '登录成功',$data);
    }

    /**
     * 用户退出
     */
	public function logout()
    {
        if( TokenService::clearAccessToken() ){
            $this->return_msg(StatusCode::SUCCESS, '退出成功');
        }else{
            $this->return_msg(StatusCode::NOTFOUND, '退出失败');
        }
    }

    /**
     * 微信扫码登录
     */
    public function wxlogin()
    {
        $data = Request::post();
        validate(ValidateAccount::class)->scene('wxlogin')->check($data);

        $code = $data['code'];
        $request_url = sprintf(
            config('weixin.open.getAccessTokenUrl'),
            config('weixin.open.appid'),
            config('weixin.open.appsecret'),
            $code
        );
        $result = https_request($request_url);
        $wxdata = json_decode($result,true);
        Log::write($result);
        if( isset($wxdata['errcode']) ){
            //throw new Exception('开放平台请求异常:' . $result['errmsg'], StatusCode::SERVER_ERROR);
        }
        //$openid = $wxdata['openid'];

        // 省略 openid验证
        $modelName = $data['from'] == 'T' ? 'Teacher' : 'Student';
        $modelName = '\app\api\model\\' . $modelName;
        $user = new $modelName();
        $userInfo =  $user->find(1)->toArray();
        $data = [
            'token'       => TokenService::generateAccessToken($userInfo),
            'expire_time' => config('api.token_expire_time'),
            'userinfo'    => $userInfo
        ];
        $this->return_msg(StatusCode::SUCCESS, '登录成功',$data);
    }
}